package com.geoboard.service;

import org.codehaus.jackson.type.TypeReference;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.geoboard.HelperVolley;
import com.geoboard.application.GeoBoardApplication;
import com.geoboard.entity.User;
import com.geoboard.tools.JacksonRequest;

public class PostUserErrorListener implements Response.ErrorListener {
	
	/**** Members **************************************************/
	private Activity mContext;
	private String TAG = this.getClass().getSimpleName();

	public PostUserErrorListener (Activity context) {
		mContext = context;
	}
	
	
	@Override
	public void onErrorResponse(VolleyError error) {
		
		//if a conflict occurs retry
		if (error.networkResponse.statusCode == 409) {
			retryCreateUser();
		} else {
	    	if (error.getMessage() != null) {
	    		Log.e(TAG, error.getMessage());
		        Toast.makeText(mContext,
		        		"Server unavailable" + error.getMessage(), Toast.LENGTH_SHORT).show();
	    	} else {
	    		Log.e(TAG, "error is null - usually means server unavailable?");
		        Toast.makeText(mContext,
		        		String.format("%d - Network unavailable", error.networkResponse.statusCode),
		        		Toast.LENGTH_SHORT).show();
	    	}
		}
	}
	
	  private void retryCreateUser() {
		  	AlertDialog.Builder alert = new AlertDialog.Builder(mContext);

	    	alert.setTitle("Welcome to Geoboard!");
	    	alert.setMessage("That username is taken - enter a different user name");

	    	// Set an EditText view to get user input 
	    	final EditText input = new EditText(mContext);
	    	alert.setView(input);

	    	alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface dialog, int whichButton) {
	    		String username = input.getText().toString();
				JacksonRequest<User> request = new JacksonRequest<User>(
										Method.POST,
										GeoBoardApplication.USER_URL + "?" + "name=" + username,
										null,
										new TypeReference<User>(){},
										new PostUserListener(mContext), 
										new PostUserErrorListener(mContext));
				request.setShouldCache(false);
				HelperVolley.getRequestQueue().add(request);
				
				Toast.makeText(mContext, "Sending request", Toast.LENGTH_SHORT).show();
	    	  }
		});

		alert.show();
	}

}
